#include "Character.h"

#include "xmlloader.h"

#include <iostream>

#include <fstream>

std::string totalfile(std::string filename)
{
	std::string ret = "";
	std::ifstream ifs ( filename.c_str(), std::ifstream::in );
	std::string line;
	if(!ifs.good())
	{
		ifs.close();
		return "";
	}
	do
	{
		line.clear();
		std::getline(ifs,line);
		ret += line + "\n";
	}
	while(ifs.good());
	ifs.close();
	return ret;
}

Character::Character()
{

}

Character::Character( const std::string& filename )
{
	rapidxml::xml_document<char> doc;
	std::string filedata = totalfile( filename ) + "\0";

	char * xmldata = new char[filedata.length()+1];
	for( unsigned int i = 0; i < filedata.length(); ++i )
		xmldata[ i ] = filedata[ i ];
	xmldata[ filedata.length() ] = '\0';
	try
	{
		doc.parse<0>( xmldata );    // 0 means default parse flags
	}
	catch( rapidxml::parse_error err )
	{
		std::cout << err.what() << std::endl;
		char * spot = err.where<char>();
		for( unsigned int i = 0; i < filedata.length(); ++i )
		{
			if( &xmldata[ i ] != spot )
				std::cout << xmldata[ i ];// << std::endl;
			else
				break;
		}
		throw -1;
	}
	rapidxml::xml_node<char> * node = doc.first_node( "entity\0" );
	StatList character, statlist;
	LoadXMLnode( character, node->first_node("character\0"), "" );
	LoadXMLnode( statlist, node->first_node("statlist\0"), "" );
	*this += character | "character";
	*this += statlist | "statlist";

	rapidxml::xml_node<char> * sibling = node->first_node("statlist\0")->next_sibling();
	do
	{
		LoadXMLnode( *this, sibling, "" );
		sibling = sibling->next_sibling();
	}
	while( sibling != node->last_node() );


	delete[]xmldata;
}

Character::~Character()
{

}
